package com.ctvit.syn.service;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctvit.framework.web.upload.ReceiveFileServlet;
import com.ctvit.struts.common.CommonFunc;

public class FileTransfer {
	private static Logger logger = LoggerFactory.getLogger(FileTransfer.class);
	public static boolean httpUpload(String httpUrl, String saveFile) {
		
		return false;
	}
	public static boolean httpTranster(String httpUrl, String fileName,String noticeid,String isNewSite) {
		int bytesum = 0;
		int byteread = 0;
		URL url = null;
		try {
			url = new URL(httpUrl);
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return false;
		}
		FileOutputStream fs=null;
		InputStream inStream=null;
		OutputStream outputStream=null;
		int bytesRead = -1;
		byte[] buffer = new byte[1204];
		try {
			URLConnection conn = url.openConnection();
			inStream = conn.getInputStream();
//			fs = new FileOutputStream(saveFile);
//
//			byte[] buffer = new byte[1204];
//			while ((byteread = inStream.read(buffer)) != -1) {
//				bytesum += byteread;
//				fs.write(buffer, 0, byteread);
//			}
			URL urlRecv = new URL(CommonFunc.remoteFileRecvUrl);
	        HttpURLConnection httpConn = (HttpURLConnection)urlRecv.openConnection();
	        httpConn.setUseCaches(false);
	        httpConn.setDoOutput(true);
	        httpConn.setRequestMethod("POST");
	        httpConn.setRequestProperty("fileName", fileName);
	        httpConn.setRequestProperty("noticeid", noticeid);
	        httpConn.setRequestProperty("isNewSite", isNewSite);
	        outputStream = httpConn.getOutputStream();
	        while ((bytesRead = inStream.read(buffer)) != -1) {
	            outputStream.write(buffer, 0, bytesRead);
	        }
	        int responseCode = httpConn.getResponseCode();
	        if (responseCode == HttpURLConnection.HTTP_OK) {
//	            BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
//	            String response = reader.readLine();
	        } else {
	        	logger.info("transfer file "+ fileName+" error=" + responseCode);
	        }
	        
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			try {
				if (outputStream!=null) outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (inStream!=null)  inStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
